<?php
/**
 * 文章详情页面文件
 * 这个页面用于显示单篇文章的完整内容和评论功能
 * 包含文章内容展示、点赞、评论发布、评论管理等功能
 * 支持已登录用户进行互动操作
 */

// 引入系统初始化文件，包含所有必要的类和函数
require_once 'includes/init.php';

// 从URL参数获取文章ID，使用getGet函数安全获取GET参数
$articleId = getGet('id', 0);
// 强制转换为整数类型，防止SQL注入和无效ID
$articleId = (int)$articleId;

// 验证文章ID是否有效
if ($articleId <= 0) {
    // ID无效，跳转到首页
    redirect('index.php');
}

// 根据文章ID从数据库获取文章的完整信息
$article = $blog->getArticleById($articleId);

// 检查文章是否存在
if (!$article) {
    // 文章不存在，跳转到首页
    redirect('index.php');
}

// 增加文章的阅读量计数
// 每次访问文章详情页都会自动增加阅读量
$blog->increaseViewCount($articleId);

// 获取文章关联的分类列表
$categories = $blog->getArticleCategories($articleId);
// 获取文章关联的标签列表
$tags = $blog->getArticleTags($articleId);

// 获取文章的所有评论列表
$comments = $blog->getComments($articleId);

// 初始化消息变量，用于显示操作结果
$message = '';      // 消息内容
$messageType = '';  // 消息类型（success/error/info）

// 处理文章点赞操作
// 检查是否提交了点赞表单
if (isPost('like_article')) {
    // 检查用户是否已登录，只有登录用户才能点赞
    if ($blog->isLoggedIn()) {
        // 调用点赞方法，返回true表示点赞成功
        if ($blog->likeArticle($articleId)) {
            // 点赞成功，重新获取文章信息以更新点赞数显示
            $article = $blog->getArticleById($articleId);
            $message = '点赞成功！感谢您的支持！';
            $messageType = 'success';
        } else {
            // 点赞失败，可能是已经点过赞或系统错误
            $message = '点赞失败，请稍后重试';
            $messageType = 'error';
        }
    } else {
        // 用户未登录，提示需要登录
        $message = '请先登录后再点赞';
        $messageType = 'error';
    }
}

// 处理评论提交功能
// 检查是否为POST请求且提交了评论表单
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_comment'])) {
    // 检查用户登录状态，只有登录用户才能发表评论
    if (!isLoggedIn()) {
        $message = '请先登录后再发表评论';
        $messageType = 'error';
    } else {
        // 获取评论内容，使用$_POST直接获取
        $content = $_POST['content'];
        
        // 验证评论内容是否为空
        if (empty($content)) {
            $message = '评论内容不能为空';
            $messageType = 'error';
        } else {
            // 从session中获取当前登录用户的ID
            $userId = $_SESSION['user_id'];
            
            // 调用博客系统的发布评论方法
            if ($blog->publishComment($articleId, $userId, $content)) {
                $message = '评论发布成功！';
                $messageType = 'success';
                // 重新获取评论列表，显示最新的评论
                $comments = $blog->getComments($articleId);
                // 重新获取文章信息，更新评论数量显示
                $article = $blog->getArticleById($articleId);
            } else {
                // 评论发布失败
                $message = '评论发布失败，请稍后重试';
                $messageType = 'error';
            }
        }
    }
}

// 处理评论删除功能
// 检查是否提交了删除评论的请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_comment'])) {
    // 检查用户是否已登录
    if (isLoggedIn()) {
        // 获取要删除的评论ID，强制转换为整数
        $commentId = (int)$_POST['comment_id'];
        // 获取当前登录用户ID，用于权限验证
        $userId = $_SESSION['user_id'];
        
        // 调用删除评论方法，只能删除自己的评论
        if ($blog->deleteComment($commentId, $userId)) {
            $message = '评论删除成功！';
            $messageType = 'success';
            // 重新获取评论列表和文章信息，更新页面显示
            $comments = $blog->getComments($articleId);
            $article = $blog->getArticleById($articleId);
        } else {
            // 删除失败，可能是权限不足或评论不存在
            $message = '评论删除失败或您没有权限删除此评论';
            $messageType = 'error';
        }
    }
}

// 处理评论编辑功能
// 检查是否提交了编辑评论的请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_comment'])) {
    // 检查用户是否已登录
    if (isLoggedIn()) {
        // 获取要编辑的评论ID
        $commentId = (int)$_POST['comment_id'];
        // 获取新的评论内容
        $newContent = getPost('new_content');
        // 获取当前用户ID用于权限验证
        $userId = $_SESSION['user_id'];
        
        // 验证新评论内容是否为空
        if (empty($newContent)) {
            $message = '评论内容不能为空';
            $messageType = 'error';
        } else {
            // 调用更新评论方法，只能编辑自己的评论
            if ($blog->updateComment($commentId, $userId, $newContent)) {
                $message = '评论更新成功！';
                $messageType = 'success';
                // 重新获取评论列表和文章信息，显示更新后的内容
                $comments = $blog->getComments($articleId);
                $article = $blog->getArticleById($articleId);
            } else {
                // 更新失败，可能是权限不足或评论不存在
                $message = '评论更新失败或您没有权限编辑此评论';
                $messageType = 'error';
            }
        }
    }
}

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo escape($article['标题']); ?> - 我的博客系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f5f5;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background: #fff;
            padding: 20px 0;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .nav {
            display: flex;
            gap: 20px;
        }
        
        .nav a {
            text-decoration: none;
            color: #333;
            padding: 8px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        
        .nav a:hover {
            background-color: #3498db;
            color: white;
        }
        
        .article-container {
            background: white;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            margin-bottom: 30px;
            position: relative;
            overflow: hidden;
        }
        
        .article-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .article-header {
            margin-bottom: 30px;
            border-bottom: 2px solid #e1e1e1;
            padding-bottom: 20px;
        }
        
        .article-title {
            font-size: 32px;
            color: #2c3e50;
            margin-bottom: 15px;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .article-meta {
            color: #666;
            font-size: 14px;
            margin-bottom: 15px;
        }
        
        /* 分类和标签样式 */
        .article-tags {
            margin: 15px 0 20px 0;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .category-tag {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);
            transition: all 0.3s ease;
        }
        
        .category-tag:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
        }
        
        .tag-item {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            box-shadow: 0 2px 4px rgba(240, 147, 251, 0.3);
            transition: all 0.3s ease;
        }
        
        .tag-item:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(240, 147, 251, 0.4);
        }
        

        
        .article-stats {
            color: #999;
            font-size: 13px;
            display: flex;
            gap: 20px;
            align-items: center;
        }
        
        .like-button {
            background: #e91e63;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .like-button:hover {
            background: #c2185b;
        }
        
        .like-button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .article-content {
            font-size: 16px;
            line-height: 1.8;
            color: #444;
            margin-bottom: 40px;
        }
        
        .article-content p {
            margin-bottom: 15px;
        }
        
        .comments-section {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            position: relative;
            overflow: hidden;
        }
        
        .comments-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        .comments-title {
            font-size: 24px;
            color: #2c3e50;
            margin-bottom: 20px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }
        
        .comment-count {
            color: #3498db;
            font-weight: bold;
        }
        
        .comment-form {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e1e1;
            border-radius: 5px;
            font-size: 14px;
            resize: vertical;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #3498db;
        }
        
        .btn {
            background: #3498db;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            transition: background-color 0.3s;
            font-size: 14px;
        }
        
        .btn:hover {
            background: #2980b9;
        }
        
        .btn-small {
            padding: 5px 10px;
            font-size: 12px;
        }
        
        .btn-danger {
            background: #e74c3c;
        }
        
        .btn-danger:hover {
            background: #c0392b;
        }
        
        .btn-warning {
            background: #f39c12;
        }
        
        .btn-warning:hover {
            background: #e67e22;
        }
        
        .btn-secondary {
            background: #95a5a6;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        
        .alert {
            padding: 12px 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .comment-list {
            margin-top: 20px;
        }
        
        .comment-item {
            padding: 20px;
            border: 1px solid #e1e1e1;
            border-radius: 12px;
            margin-bottom: 15px;
            position: relative;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            transition: all 0.3s ease;
        }
        
        .comment-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            border-color: #667eea;
        }
        
        .comment-item:last-child {
            margin-bottom: 0;
        }
        
        .comment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .comment-author {
            font-weight: bold;
            color: #2c3e50;
        }
        
        .comment-date {
            color: #666;
            font-size: 12px;
        }
        
        .comment-content {
            color: #555;
            line-height: 1.6;
            margin-bottom: 10px;
        }
        
        .comment-actions {
            display: flex;
            gap: 10px;
        }
        
        .comment-edit-form {
            display: none;
            margin-top: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .comment-edit-form.active {
            display: block;
        }
        
        .no-comments {
            text-align: center;
            color: #666;
            padding: 40px;
        }
        
        .back-link {
            text-align: center;
            margin: 20px 0;
        }
        
        .back-link a {
            color: #3498db;
            text-decoration: none;
            font-size: 14px;
        }
        
        .back-link a:hover {
            text-decoration: underline;
        }
        
        .auto-update {
            background: #e8f4fd;
            border: 1px solid #bee5eb;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 20px;
            font-size: 14px;
            color: #0c5460;
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <div class="header-content">
                <div class="logo">我的博客系统</div>
                <nav class="nav">
                    <a href="index.php">首页</a>
                    <?php if (isLoggedIn()): ?>
                        <a href="admin/index.php">管理后台</a>
                        <a href="admin/post.php">发布文章</a>
                        <a href="logout.php">退出登录</a>
                    <?php else: ?>
                        <a href="login.php">登录</a>
                        <a href="register.php">注册</a>
                    <?php endif; ?>
                </nav>
            </div>
        </div>
    </header>

    <div class="container">
        <div class="back-link">
            <a href="index.php">← 返回首页</a>
        </div>
        
        <article class="article-container">
            <header class="article-header">
                <h1 class="article-title"><?php echo escape($article['标题']); ?></h1>
                
                <div class="article-meta">
                    作者：<?php echo escape($article['用户名']); ?> | 
                    发布时间：<?php echo formatDate($article['创建时间']); ?>
                    <?php if ($article['创建时间'] != $article['更新时间']): ?>
                        | 更新时间：<?php echo formatDate($article['更新时间']); ?>
                    <?php endif; ?>
                </div>
                
                <!-- 分类和标签显示 -->
                <?php if (!empty($categories) || !empty($tags)): ?>
                <div class="article-tags">
                    <?php if (!empty($categories)): ?>
                        <?php foreach ($categories as $category): ?>
                            <span class="category-tag">📂 <?php echo escape($category['分类名']); ?></span>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    
                    <?php if (!empty($tags)): ?>
                        <?php foreach ($tags as $tag): ?>
                            <span class="tag-item">🏷️ <?php echo escape($tag['标签名']); ?></span>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                
                <div class="article-stats">
                    <span>阅读：<?php echo $article['阅读量']; ?></span>
                    <span>评论：<span class="comment-count" id="comment-count"><?php echo $article['评论量']; ?></span></span>
                    
                    <form method="POST" style="display: inline;">
                        <button type="submit" name="like_article" class="like-button" 
                                <?php echo !isLoggedIn() ? 'disabled title="请先登录"' : ''; ?>>
                            ❤️ <?php echo $article['点赞量']; ?>
                        </button>
                    </form>
                </div>
            </header>
            
            <?php if (!empty($article['图片'])): ?>
                <div class="article-image-container" style="text-align: center; margin-bottom: 30px;">
                    <img src="<?php echo escape($article['图片']); ?>" alt="<?php echo escape($article['标题']); ?>" 
                         style="max-width: 100%; max-height: 400px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
                </div>
            <?php endif; ?>
            
            <div class="article-content">
                <?php echo nl2br(escape($article['内容'])); ?>
            </div>
        </article>
        
        <section class="comments-section">
            <h2 class="comments-title">评论区 (<span id="comment-display-count"><?php echo count($comments); ?></span>)</h2>
            
            <div class="auto-update">
                💡 评论数量会自动更新，无需刷新页面
            </div>
            
            <?php if (!empty($message)): ?>
                <div class="alert alert-<?php echo $messageType; ?>" id="message-alert">
                    <?php echo escape($message); ?>
                </div>
            <?php endif; ?>
            
            <?php if (isLoggedIn()): ?>
                <form method="POST" class="comment-form" id="comment-form">
                    <div class="form-group">
                        <label for="content">发表评论</label>
                        <textarea id="content" name="content" class="form-control" rows="4" 
                                  placeholder="请输入您的评论内容..." required></textarea>
                    </div>
                    <button type="submit" name="submit_comment" class="btn">发表评论</button>
                </form>
            <?php else: ?>
                <div class="comment-form">
                    <p style="text-align: center; color: #666;">
                        <a href="login.php" class="btn">登录</a> 后发表评论
                    </p>
                </div>
            <?php endif; ?>
            
            <div class="comment-list" id="comment-list">
                <?php if (empty($comments)): ?>
                    <div class="no-comments" id="no-comments">
                        <p>暂无评论，快来发表第一条评论吧！</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($comments as $index => $comment): ?>
                        <?php
                        // 使用新的评论ID字段进行权限控制
                        $commentId = $comment['comment_id'];
                        $canEdit = isLoggedIn() && $comment['评论用户ID'] == $_SESSION['user_id'];
                        ?>
                        <div class="comment-item">
                            <div class="comment-header">
                                <span class="comment-author"><?php echo escape($comment['用户名']); ?></span>
                                <span class="comment-date"><?php echo formatDate($comment['评论时间']); ?></span>
                            </div>
                            <div class="comment-content" id="content-<?php echo $commentId; ?>">
                                <?php echo nl2br(escape($comment['评论内容'])); ?>
                            </div>
                            
                            <?php if ($canEdit): ?>
                                <div class="comment-actions">
                                    <button onclick="toggleEditForm(<?php echo $commentId; ?>)" class="btn btn-warning btn-small">编辑</button>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('确定要删除这条评论吗？')">
                                        <input type="hidden" name="comment_id" value="<?php echo $commentId; ?>">
                                        <button type="submit" name="delete_comment" class="btn btn-danger btn-small">删除</button>
                                    </form>
                                </div>
                                
                                <div class="comment-edit-form" id="edit-form-<?php echo $commentId; ?>">
                                    <form method="POST">
                                        <input type="hidden" name="comment_id" value="<?php echo $commentId; ?>">
                                        <div class="form-group">
                                            <textarea name="new_content" class="form-control" rows="3" required><?php echo escape($comment['评论内容']); ?></textarea>
                                        </div>
                                        <button type="submit" name="edit_comment" class="btn btn-warning btn-small">保存</button>
                                        <button type="button" onclick="toggleEditForm(<?php echo $commentId; ?>)" class="btn btn-secondary btn-small">取消</button>
                                    </form>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>
    </div>

    <script>
        // 编辑评论功能
        function toggleEditForm(commentId) {
            const editForm = document.getElementById('edit-form-' + commentId);
            const isActive = editForm.classList.contains('active');
            
            // 隐藏所有编辑表单
            document.querySelectorAll('.comment-edit-form').forEach(form => {
                form.classList.remove('active');
            });
            
            // 切换当前表单
            if (!isActive) {
                editForm.classList.add('active');
            }
        }

        // 自动隐藏消息提示
        setTimeout(function() {
            const alert = document.getElementById('message-alert');
            if (alert) {
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }
        }, 5000);

        // 表单提交后清空内容
        document.getElementById('comment-form')?.addEventListener('submit', function(e) {
            setTimeout(() => {
                document.getElementById('content').value = '';
            }, 1000);
        });
    </script>
</body>
</html> 